import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import {
  Toast,
  Indicator
} from 'mint-ui';
import router from '../router/index';
import CONFIG from "./CONFIG.js";

axios.defaults.baseURL = CONFIG.URL.APIHOST; //配置接口地址
axios.defaults.timeout = CONFIG.URL.APITIME; // 超时时间
let locationURL = CONFIG.URL.APIHOSTLOCA; //省市区接口(及部分接口)
axios.create({
  withCredentials: true
})

// 请求时的拦截
axios.interceptors.request.use(
  config => {
    // 发送请求之前做一些处理
    Indicator.open('加载中...');
    config.data = qs.stringify(config.data);
    config.headers = {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      'X-Requested-With': 'XMLHttpRequest'
    }
    if (config.method === 'get') {
      config.headers['Accept'] = "application/json";
    }
    let token = localStorage.getItem('token');
    if (token) {
      config.headers['token'] = token
    }
    return config;
  },
  error => {
    // 当请求异常时做一些处理
    Indicator.close(); //隐藏loading
    console.log('---请求异常关闭----');
    return Promise.reject(err);
  }
);

// 响应时拦截
axios.interceptors.response.use(
  response => {
    console.log('---响应关闭----');
    // 返回响应时做一些处理
    Indicator.close(); //隐藏loading
    if (response.data.code == 0) {
      return Promise.resolve(response.data.data);
    } else {
      Toast({
        message: response.data.msg,
        position: 'bottom',
        duration: 3000
      });
    }
  },
  error => {
    // 当响应异常时做一些处理
    console.log('---异常异常----');
    Toast({
      message: response.data.msg,
      position: 'bottom',
      duration: 3000
    });
    return Promise.reject(error)
  }
);
export default {axios}

